var difLat = 0;
var difLon = 0;
var aircraftMarker;
var aircraftDrive=false;
var currentViewedItem = null;
var currentItem = [];

function playAircraft(aircraft,username){
	var lat = aircraft.lat;
	var lon = aircraft.lon;
	var prevLat;
	var prevLon;
	var marker = insertMarker('images/aircraft1/aircraft1_0.png',lat,lon);
	
	$.ajax({
		   type: "POST",
		   url: "/FlightGame/app/flight/create",
		   data:"username="+username+"&itemname="+aircraft.itemname+"&id="+aircraft.id,
		   success: function(json){
			   aircraftDrive=true;
		   }
		 });

	aircraftMarker = marker;
	
	var flightUpdate = window.setInterval(function (a,b) {
		prevLat = lat;
		prevLon = lon;
		
		lat += difLat;
		lon += difLon;
		
		setUIValue('aircraftSpeedLabel',calculateSpeed(prevLat,prevLon,lat,lon));
		
		if(lon >= 180) lon -=360;
		else if(lon < -180) lon += 360;
		changeMarkerPosition(marker, lat,lon);
		
		googleMap.setCenter(new google.maps.LatLng(lat,lon));

		
		if(currentViewedItem != null){
			setUIValue('aircraftLatitude',lat);
			setUIValue('aircraftLongitude',lon);
			setUIValue('distance',Math.round(calculateDistance(lat,lon,currentViewedItem.lat,currentViewedItem.lon)));
		}
			
	},flightUpdateTime);
	
	var radarUpdate = window.setInterval(function (a,b) {
		var json = refreshPosition(aircraft.id, lat, lon,0);
		//if($( "#distanceFromOwnership" )) $( "#distanceFromOwnership" ).text(lat);
	},radarUpdateTime);

	currentItem.push([aircraft,radarUpdate,flightUpdate]);
}

function getAircraft(ownerships,id){
	
	for(var i=0;i < ownerships.length ; i++){
		if(ownerships[i].id == id) return ownerships[i];
	}
	
	return null;
}


function keyPressHandler(event) {
	var inc = 0.01;
	var lim = 0.06;
	if(aircraftDrive == true){
		if(event.keyCode == 37){ // left
			difLon -= inc;
		}
		else if(event.keyCode == 39){ // right
			difLon += inc;
		}
		else if(event.keyCode == 38){ // up
			difLat += inc;
		}
		else if(event.keyCode == 40){ // down
			difLat -= inc;
		}
		
		if(difLon > lim) difLon = lim;
		if(difLat > lim) difLat = lim;
		if(difLon < -lim) difLon = -lim;
		if(difLat < -lim) difLat = -lim;
		rotateAircraft(aircraftMarker,difLon,difLat,true);
	}
  }

function rotateAircraft(aircraftmarker,diflon,diflat,setIcon){
	var angle = (180/Math.PI) * Math.atan2(diflon,diflat);
	var diff = 15;
	angle = Math.round(angle);
	var roundedAngle = Math.round(angle / diff) * diff;
	
	if(roundedAngle == -180) roundedAngle = 180;
	
	if(setIcon == true) aircraftmarker.setIcon('images/aircraft1/aircraft1_'+roundedAngle+'.png');
	
	return roundedAngle;
}

function refreshPosition(aircraftId,lat,lon,alt){
	var currentBounds = getCurrentBounds(true);
	
	var lon1 = currentBounds[1];
	var lon2 = currentBounds[3];
	var lat1 = currentBounds[0];
	var lat2 = currentBounds[2];
	var difLat = lat2 - lat1;
	var difLon = lon2 - lon1;
	
	var radarRange = lat1 + ',' + lat2 + ',' + lon1 + ',' + lon2;
	
	$.ajax({
		   type: "POST",
		   url: "/FlightGame/app/flight/refresh",
		   data:"id="+aircraftId+"&lat="+lat+"&lon="+lon+"&alt="+alt+'&radar='+radarRange,
		   dataType: "json",
		   success: function(json){
			   viewAirports(json.airports);
			   setUIValue('aircraftFuelLabel',json.fuel);
			   viewAircrafts(json,aircraftId);
			   getOwnershipsAround();
			   if(json.messages.length > 0)
				   generateHtmlPopupData(json.messages,'message');
		   }
		 });
}

function getCurrentBounds(radar){
	var bounds = [];
	var currentBounds = googleMap.getBounds();
	
	var lat1 = currentBounds.getSouthWest().lat();
	var lat2 = currentBounds.getNorthEast().lat();
	var lon1 = currentBounds.getSouthWest().lng();
	var lon2 = currentBounds.getNorthEast().lng();
	
	
	
	if(radar == true){
		var difLat = lat2 - lat1;
		var difLon = lon2 - lon1;
		
		lat1 -= difLat/2;
		lat2 += difLat/2;
		lon1 -= difLon/2;
		lon2 += difLon/2;
	}
	
	if(lon1 < -180) lon1 = -179.9999;
	if(lon2 > 180) lon2 = 179.9999;
	if(lon1 > 180) lon1 = 179.9999;
	if(lon2 < -180) lon2 = -179.9999;
	
	if(lon1 > 0 && lon2 < 0) lon2 = 179.9999;
	
	bounds.push(lat1);
	bounds.push(lon1);
	bounds.push(lat2);
	bounds.push(lon2);
	
	return bounds;
}

function buyFuel(lat,lon){
	difLat = 0;
	difLon = 0;
	
}
function getOwnershipsAround(){
	var currentBounds = getCurrentBounds(true);
	
	var lon1 = currentBounds[1];
	var lon2 = currentBounds[3];
	var lat1 = currentBounds[0];
	var lat2 = currentBounds[2];
	
	$.ajax({
		   type: "GET",
		   url: "/FlightGame/app/json/ownershipsaround/"+lat1+'/'+lon1+'/'+lat2+'/'+lon2,
		   dataType: "json",
		   success: function(json){
				   var ownerships = json.ownerships;
				   clearOwnershipsAround();
				   for(var i=0;i<ownerships.length;i++){
					   if(ownerships[i].type != 'aircraft'){
						   var marker = insertMarker('images/'+ownerships[i].itemname+'.png',ownerships[i].lat,ownerships[i].lon);
						  
						   ownershipsAround.push([ownerships[i],marker]);
						   
					   }
				   }
				   // Ownership Data Window
				   for(var i=0 ; i < ownershipsAround.length ; i++){
						google.maps.event.addListener(ownershipsAround[i][1], 'click', function(){
							var ownership = getMarkerItem(this,'ownership');
							
							generateHtmlPopupData(ownership,'ownership');

						});
					}
		   }
		 });
}

document.onkeydown = keyPressHandler;
